#include "jwaitbox.h"
#include "ui_jwaitbox.h"

#include <QApplication>
#include <QEventLoop>
#include <QCloseEvent>

namespace QTE
{

class Q_DECL_HIDDEN JWaitBoxPrivate
{
public:
	JWaitBoxPrivate(JWaitBox *wb);
	~JWaitBoxPrivate();

public:
	Ui::JWaitBox *ui;
	QEventLoop m_eventLoop;
};

JWaitBoxPrivate::JWaitBoxPrivate(JWaitBox *wb) :
	ui(new Ui::JWaitBox)
{
	ui->setupUi(wb);
	ui->pb_cancel->hide();
	ui->wait_bar->start();
}

JWaitBoxPrivate::~JWaitBoxPrivate()
{
	delete ui;
}

/*-------------------------------------------------------------------------------*/

JWaitBox::JWaitBox(QWidget *parent) :
	QWidget(parent),
	d_ptr(new JWaitBoxPrivate(this))
{
	showWaitBar(200);
	setWindowModality(Qt::WindowModal);

	connect(d_ptr->ui->pb_cancel, &QPushButton::clicked, this, &JWaitBox::cancel);
}

JWaitBox::JWaitBox(const QString &msg, QWidget *parent) :
	JWaitBox(parent)
{
	d_ptr->ui->lb_msg->setText(msg);
}

JWaitBox::~JWaitBox()
{
	delete d_ptr;
}

void JWaitBox::exec(bool fill)
{
	if( fill )
		showFullScreen();
	d_ptr->m_eventLoop.exec(QEventLoop::DialogExec);
}

void JWaitBox::setMessage(const QString &msg)
{
	d_ptr->ui->lb_msg->setText(msg);
}

void JWaitBox::setCancelButtonVisible(bool visible)
{
	d_ptr->ui->pb_cancel->setVisible(visible);
}

void JWaitBox::setCancelButtonText(const QString &text)
{
	d_ptr->ui->pb_cancel->setText(text);
}

void JWaitBox::setWaitBar(JWaitBar *bar)
{
	Q_ASSERT_X(bar, "JWaitBox::setWaitBar", "Wait bar is NULL.");

	d_ptr->ui->wait_bar->deleteLater();
	d_ptr->ui->wait_bar = bar;
}

void JWaitBox::showWaitBar(int msecs)
{
	d_ptr->ui->wait_bar->show();
	d_ptr->ui->wait_bar->start(msecs);
}

const JWaitBar *JWaitBox::waitBar() const
{
	return d_ptr->ui->wait_bar;
}

JWaitBar *JWaitBox::waitBar()
{
	return d_ptr->ui->wait_bar;
}

void JWaitBox::hideWaitBar()
{
	d_ptr->ui->wait_bar->hide();
	d_ptr->ui->wait_bar->stop();
}

JWaitBox &JWaitBox::globalInstance(const QString &msg)
{
	static JWaitBox jwb;

	if( not msg.isNull() )
		jwb.setMessage(msg);

	return jwb;
}

void JWaitBox::closeEvent(QCloseEvent *event)
{
	d_ptr->m_eventLoop.quit();
	event->accept();
}

void JWaitBox::changeEvent(QEvent *event)
{
	QWidget::changeEvent(event);

	if( event->type() == QEvent::FontChange )
	{
		d_ptr->ui->lb_msg->setFont(font());
		d_ptr->ui->pb_cancel->setFont(font());
	}
}

} //namespace JXQ
